﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;

namespace MOKA.TPM.Utility
{
    public class HttpClientHelper
    {
        public Collection<Cookie> Cookies { get; set; }
        public string BaseAddress { get; set; }
        public int Timeout { get; set; }
        public Dictionary<string, string> ResponseHeaders { get; set; }

        public HttpClientHelper()
        {
            Cookies = null;
            BaseAddress = "";
            Timeout = 60;
            this.ResponseHeaders = new Dictionary<string, string>();
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="API"></param>
        /// <param name="requestData"></param>
        /// <returns></returns>
        public dynamic Post(string url, string requestData, Dictionary<string, string> RequestHeaders = null)
        {
            try
            {
                var handler = new HttpClientHandler();
                if (Cookies != null && Cookies.Count > 0)
                {
                    // 创建一个 CookieContainer 并添加 Cookie
                    var cookieContainer = new CookieContainer();
                    // cookieContainer.Add(new Uri(url), new Cookie("session-id", "your-session-id"));

                    foreach (Cookie cookie in Cookies)
                    {
                        if (!string.IsNullOrEmpty(BaseAddress))
                            cookieContainer.Add(new Uri(BaseAddress), cookie);
                        else
                            cookieContainer.Add(cookie);
                    }

                    // 使用 HttpClientHandler 设置 CookieContainer
                    handler.CookieContainer = cookieContainer;
                }
                var client = new HttpClient(handler);
                if (!string.IsNullOrEmpty(BaseAddress))
                {
                    client.BaseAddress = new Uri(BaseAddress);
                }
                client.Timeout = TimeSpan.FromSeconds(Timeout);

                // 创建 HttpRequestMessage
                var request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = new StringContent(requestData)
                {
                    Headers =
                            {
                                ContentType = new MediaTypeHeaderValue("application/json")
                            }
                };

                if (RequestHeaders != null)
                {
                    foreach (var header in RequestHeaders)
                    {
                        // 检查是否可以添加头，因为某些头可能需要特殊处理
                        request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }

                using (var response = client.SendAsync(request).Result)
                {
                    SetResponseHeaders(response);
                    response.EnsureSuccessStatusCode();
                    // 获取响应中的 Cookie
                    //Uri uri = new Uri("https://yourapi.com");
                    // CookieCollection cookies = cookieContainer.GetCookies(uri);

                    // 获取特定的响应头
                    //string headerName = "access-token"; // 你想要获取的头的名称
                    //IEnumerable<string> headerValues;
                    //if (response.Headers.TryGetValues(headerName, out  headerValues))
                    //{
                    //    // 输出特定头的值
                    //    Console.WriteLine(headerName + ":" + string.Join(", ", headerValues));
                    //}
                    if (response.Content.Headers.ContentType.MediaType == "application/octet-stream")
                    {
                        MemoryStream memoryStream = new MemoryStream();
                        var stream = response.Content.ReadAsStreamAsync().Result;
                        stream.CopyTo(memoryStream);
                        memoryStream.Position = 0;
                        return memoryStream;
                    }
                    else
                    {
                        var body = response.Content.ReadAsStringAsync().Result;
                        return body;
                    }
                }
            }
            catch (Exception e)
            {
                throw new NotImplementedException(e.Message);
            }
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="API"></param>
        /// <param name="requestData"></param>
        /// <returns></returns>
        public dynamic Get(string url, string urlParam = null, Dictionary<string, string> RequestHeaders = null)
        {
            try
            {
                var handler = new HttpClientHandler();
                if (Cookies != null && Cookies.Count > 0)
                {
                    // 创建一个 CookieContainer 并添加 Cookie
                    var cookieContainer = new CookieContainer();
                    // cookieContainer.Add(new Uri(url), new Cookie("session-id", "your-session-id"));

                    foreach (Cookie cookie in Cookies)
                    {
                        if (!string.IsNullOrEmpty(BaseAddress))
                            cookieContainer.Add(new Uri(BaseAddress), cookie);
                        else
                            cookieContainer.Add(cookie);
                    }

                    // 使用 HttpClientHandler 设置 CookieContainer
                    handler.CookieContainer = cookieContainer;
                }

                var client = new HttpClient(handler);
                if (!string.IsNullOrEmpty(BaseAddress))
                {
                    client.BaseAddress = new Uri(BaseAddress);
                }
                client.Timeout = TimeSpan.FromSeconds(Timeout);

                string urlParams = "";
                if (!string.IsNullOrEmpty(urlParam))
                {
                    // 将 JSON 字符串转换为字典
                    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(urlParam);

                    // 将字典转换为 URL 参数
                    urlParams = "?" + HttpHelper.ConvertToUrlParams(dictionary);
                }

                var request = new HttpRequestMessage(HttpMethod.Get, url + urlParams);

                if (RequestHeaders != null)
                {
                    foreach (var header in RequestHeaders)
                    {
                        // 检查是否可以添加头，因为某些头可能需要特殊处理
                        request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }
                using (var response = client.SendAsync(request).Result)
                {
                    SetResponseHeaders(response);
                    response.EnsureSuccessStatusCode();
                    if (response.Content.Headers.ContentType.MediaType == "application/octet-stream")
                    {
                        MemoryStream memoryStream = new MemoryStream();
                        var stream = response.Content.ReadAsStreamAsync().Result;
                        stream.CopyTo(memoryStream);
                        memoryStream.Position = 0;
                        return memoryStream; //返回一个Stream

                        //msg.Data   = new FileStreamResult(memoryStream, "application/octet-stream") { FileDownloadName = "ab.pdf" };
                    }
                    else
                    {
                        var body = response.Content.ReadAsStringAsync().Result;
                        return body;//返回一个字符串
                    }
                }
            }
            catch (Exception e)
            {
                throw new NotImplementedException(e.Message);
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath"></param>
        /// <param name="RequestHeaders"></param>
        /// <returns></returns>
        public dynamic PostFile(string url, string filePath, Dictionary<string, string> RequestHeaders = null)
        {
            try
            {
                var handler = new HttpClientHandler();
                if (Cookies != null && Cookies.Count > 0)
                {
                    // 创建一个 CookieContainer 并添加 Cookie
                    var cookieContainer = new CookieContainer();
                    // cookieContainer.Add(new Uri(url), new Cookie("session-id", "your-session-id"));

                    foreach (Cookie cookie in Cookies)
                    {
                        if (!string.IsNullOrEmpty(BaseAddress))
                            cookieContainer.Add(new Uri(BaseAddress), cookie);
                        else
                            cookieContainer.Add(cookie);
                    }

                    // 使用 HttpClientHandler 设置 CookieContainer
                    handler.CookieContainer = cookieContainer;
                }

                var client = new HttpClient(handler);
                if (!string.IsNullOrEmpty(BaseAddress))
                {
                    client.BaseAddress = new Uri(BaseAddress);
                }
                client.Timeout = TimeSpan.FromSeconds(Timeout);

                // 创建 HttpRequestMessage
                using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                {
                    // 将头添加到请求
                    if (RequestHeaders != null)
                    {
                        foreach (var header in RequestHeaders)
                        {
                            // 检查是否可以添加头，因为某些头可能需要特殊处理
                            request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                        }
                    }

                    // 创建 MultipartFormDataContent
                    var content = new MultipartFormDataContent();
                    // content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
                    fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");//new MediaTypeHeaderValue("image/jpeg"); // 根据文件类型设置
                    content.Add(fileContent, "file", Path.GetFileName(filePath));

                    // 将内容添加到请求
                    request.Content = content;
                    using (var response = client.SendAsync(request).Result)
                    {
                        SetResponseHeaders(response);
                        response.EnsureSuccessStatusCode();
                        var body = response.Content.ReadAsStringAsync().Result;
                        return body;
                    }
                }
            }
            catch (Exception e)
            {
                throw new NotImplementedException(e.Message);
            }
        }

        private void SetResponseHeaders(HttpResponseMessage response)
        {
            this.ResponseHeaders.Clear();
            foreach (KeyValuePair<string, IEnumerable<string>> header in (HttpHeaders)response.Headers)
            {
                foreach (string str in header.Value)
                    this.ResponseHeaders.Add(header.Key, str);
            }
        }
    }
}